import main.kotlin.gui.MyApp
import javafx.application.Application
import kotlin.text.Regex
import org.apache.commons.cli.*
import main.kotlin.singlePage.SinglePage

/**
 * 主函数，运行单页下载器
 */

fun proxyValidator(proxy: String): List<String>? {
    val ip = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\." +
        "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\." +
        "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\." +
        "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"


    val pattern = Regex("^(?<ip>$ip):(?<port>\\d+)$")

    val matched = pattern.find(proxy)?.groupValues

    if (matched == null ) {
        return null
    } else {
        return listOf(matched[1], matched[matched.lastIndex])
    }
}


fun main(args: Array<String>) {
    val options = Options()

    val help = Option(
            "h", "help", false,"帮助信息"
    )
    options.addOption(help)

    val url = Option(
            "u", "url", true, "CL图片页面的URL"
    )
    options.addOption(url)

    val outfile = Option(
            "o", "outdir", true, "输出文件夹"
    )
    options.addOption(outfile)

    val proxy = Option(
            "x", "proxy", true, "代理"
    )
    options.addOption(proxy)

    val prefix = Option(
            "p", "prefix", true, "输出文件的前缀名，默认为same，表明使用文章题目为文件名"
    )
    options.addOption(prefix)

    val style = Option(
            "s", "style", true, "输出html的风格，默认为self（自定义风），还有pixyll、github、newsprint、night、whitey"
    )
    options.addOption(style)

    val gui = Option(
            "g", "gui", false, "打开GUI"
    )
    options.addOption(gui)

    val parser: CommandLineParser = DefaultParser()
    val formatter = HelpFormatter()
    val cmd: CommandLine

    try {
        cmd = parser.parse(options, args)
    } catch (e: ParseException ) {
        println(e.message)
        return
    }

    if (args.isEmpty() || cmd.hasOption("gui")) {
        try{
            Application.launch(MyApp::class.java, *args)
        } catch (e:Exception) {
            println(e.message)
        }
        return
    }

    if (cmd.hasOption("help") || !cmd.hasOption("url")) {
        formatter.printHelp("单页下载器", options)
        return
    }

    val crawler = SinglePage(
            cmd.getOptionValue("url").toString(), "GBK"
    )

    if (cmd.hasOption("proxy")) {
        val proxySetting = proxyValidator(cmd.getOptionValue("proxy"))

        if (proxySetting != null) {crawler.proxy = proxySetting }
    }

    var outPrefix = "same"

    if (cmd.hasOption("prefix")) {
        outPrefix = cmd.getOptionValue("prefix").toLowerCase().trim()
    }

    var styleS = "self"
    if (cmd.hasOption("style")) {
        styleS = cmd.getOptionValue("style")
    }

    if (cmd.hasOption("outdir")) {
        crawler.saveTo(cmd.getOptionValue("outdir"), prefix = outPrefix, style = styleS)
    } else {
        crawler.saveTo(prefix = outPrefix, style = styleS)
    }
}
